/**
 * @author Stephan Pfaff (webmaster@derdaumen.net)
 */

var libPath = '../lib/php/';
var noImage = "../css/backend/screen/images/noImage.png";

var debug = true;
var categories = null;
var projects = null;
var buttons = null;

var imgwidth = 75;
var imgheight = 75;
var tempPath = '';

var maxImgSize = '10MB';

var cropDialog = null;

function getCategories(){
	if(categories == null) {
		categories = $('#select_category');
		var categoryContainer = new ItemContainer('category',
				'ctg',
				libPath+'load.php',
				libPath+'save.php',
				libPath+'new.php',
				libPath+'delete.php');
		$.extend(categories, categoryContainer);
	}
	return categories;
};

function getProjects(){
	if(projects == null) {
		projects = $('#select_project');
		var projectContainer = new ItemContainer('project',
				'prj',
				libPath+'load.php',
				libPath+'save.php',
				libPath+'new.php',
				libPath+'delete.php');
		$.extend(projects, projectContainer);
	}
	return projects;
};

function getButtons(){
	if(buttons == null) {
		buttons = $('#select_button');
		var buttonContainer = new ItemContainer('button',
				'btn',
				libPath+'load.php',
				libPath+'save.php',
				libPath+'new.php',
				libPath+'delete.php');
		$.extend(buttons, buttonContainer);
	}
	return buttons;
};

function focus(container) {
	switch(container.type) {
		case getCategories.type:
			getProjects.clearFormElements(true);
			getButtons.clearFormElements(true);
			break;
		case getProjects.type:
			getButtons.clearFormElements(true);
			break;
		default:
			break;
	}
}

/*
 * ############################################################################
 * ################################## Main ####################################
 * ############################################################################
 */

function init() {
	$('.yform').clearForm();
	getCategories();
	getProjects();
	getButtons();
	getCategories().load({prefix: getCategories().prefix}, null, true);
	
	/*
	 * #########################################################################
	 * ############################# Category Buttons ##########################
	 * #########################################################################
	 */
	
	$('#select_category').focus( function() {
		focus(getCategories());
		getCategories().change();
	});
	$('#select_category').change( function() {
		getCategories().change();
	});
	$('#btn_saveCtg').click( function() {
		this.blur();
		getCategories().saveItem();
	});

	// New Category Dialog			
	$('#dialog_newCtg').dialog({
		autoOpen: false,
		width: 250,
		buttons: {
			"Ok": function() {
				if ($('#ctg_new_alias').val() != '') {
					$('#ctg_alias').val($('#ctg_new_alias').val());
					$('#ctg_new_alias').val('');
					getCategories().newItem();
					$(this).dialog("close");
				} else {
					alert('Ein Alias ist notwendig!');
				}
			}, 
			"Cancel": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	
	$('#btn_newCtg').click( function() {
		this.blur();
		getCategories().clearFormElements(false);
		$('#dialog_newCtg').dialog('open');
	});
	$('#btn_resetCtg').click( function() {
		this.blur();
		$('#select_category').focus().change();
	});
	$('#btn_deleteCtg').click( function() {
		this.blur();
		if (getCategories().currentItem().id != 0) {
			getCategories().deleteItem();
		} else {
			alert('Kann nicht gelöscht werden!');
		}
	});
	
	/*
	 * #########################################################################
	 * ############################# Project Buttons ###########################
	 * #########################################################################
	 */
	
	$('#select_project').focus( function() {
		focus(getProjects());
		getProjects().change();
	});
	$('#select_project').change( function() {
		getProjects().change();
	});
	$('#btn_savePrj').click( function() {
		this.blur();
		getProjects().saveItem();
	});
	// New Project Dialog			
	$('#dialog_newPrj').dialog({
		autoOpen: false,
		width: 250,
		buttons: {
			"Ok": function() {
				if ($('#prj_new_alias').val() != '') {
					$('#prj_alias').val($('#prj_new_alias').val());
					$('#prj_new_alias').val('');
					getProjects().newItem();
					$(this).dialog("close");
				} else {
					alert('Ein Alias ist notwendig!');
				}
			}, 
			"Cancel": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	
	$('#btn_newPrj').click( function() {
		this.blur();
		getProjects().clearFormElements(false);
		$('#dialog_newPrj').dialog('open');
	});
	$('#btn_resetPrj').click( function() {
		this.blur();
		$('#select_project').focus().change();
	});
	$('#btn_deletePrj').click( function() {
		this.blur();
		getProjects().deleteItem();
	});
	
	/*
	 * #########################################################################
	 * ############################# Button Buttons ############################
	 * #########################################################################
	 */
	
	$('#select_button').focus( function() {
		focus(getButtons());
		getButtons().change();
	});
	$('#select_button').change( function() {
		getButtons().change();
	});
	$('#btn_saveBtn').click( function() {
		this.blur();
		getButtons().saveItem();
	});
	// New Button Dialog			
	$('#dialog_newBtn').dialog({
		autoOpen: false,
		width: 250,
		buttons: {
			"Ok": function() {
				if ($('#btn_new_alias').val() != '') {
					$('#btn_alias').val($('#btn_new_alias').val());
					$('#btn_new_alias').val('');
					getButtons().newItem();
					$(this).dialog("close");
				} else {
					alert('Ein Alias ist notwendig!');
				}
			}, 
			"Cancel": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	
	$('#btn_newBtn').click( function() {
		this.blur();
		getButtons().clearFormElements(false);
		$('#dialog_newBtn').dialog('open');
	});
	$('#btn_resetBtn').click( function() {
		this.blur();
		$('#select_button').focus().change();
	});
	$('#btn_deleteBtn').click( function() {
		this.blur();
		getButtons().deleteItem();
	});
	
	/*
	 * #########################################################################
	 * ############################# Text Editor ###############################
	 * #########################################################################
	 */
	
	$('#btn_text').tinymce({
		// Location of TinyMCE script
		script_url : '../lib/js/backend/plugins/tinymce/jscripts/tiny_mce/tiny_mce.js',

		// General options
		theme : "advanced",
		plugins : "style,table,save,advhr,advlink,inlinepopups,insertdatetime,preview,searchreplace,contextmenu,paste,fullscreen,visualchars,nonbreaking,xhtmlxtras",

		// Theme options
		theme_advanced_buttons1 : "save,|,undo,redo,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,cleanup,code,|,fullscreen,|,help",
		theme_advanced_buttons2 : "formatselect,fontselect,fontsizeselect,|,bullist,numlist,|,outdent,indent,blockquote",
		theme_advanced_buttons3 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,removeformat,visualaid,|,sub,sup,|,charmap,advhr",
		theme_advanced_buttons4 : "link,unlink,anchor,|,preview,|,forecolor,backcolor,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		
		apply_source_formatting : false,
		
		// Example content CSS (should be your site CSS)
		content_css : "../css/frontend/layout.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
	
	/*
	 * #########################################################################
	 * ############################# Image Upload ##############################
	 * #########################################################################
	 */
	
	// Img Upload Dialog			
	cropDialog = $('#dialog_crop').dialog({
		autoOpen: false,
		width: 800,
		modal: true,
		open: function(event, ui) {
		},
		close: function(event, ui) {
			$('.swfupload').show();
		},
		buttons: {
			"Ok": function() {
				$(this).dialog("close");
				cropDialog.container.getInstance().saveThumb();
			}, 
			"Cancel": function() {
				$(this).dialog("close");
			} 
		}
	});
	
	cropDialog.container = null;
	
	$('#btn_img_upload_container').swfupload({
		upload_url: "../lib/php/uploadImage.php",
		file_size_limit : maxImgSize,
		file_types : "*.jpg;*.png;*.gif;*.jpeg",
		file_types_description : "Web Image Files",
		file_upload_limit : "0",
		flash_url : "../lib/js/backend/plugins/swfUpload/swfupload.swf",
		button_image_url : '../css/backend/screen/images/swfupload.png',
		button_width : 61,
		button_height : 22,
		button_placeholder : $('#btn_img_upload_btn')[0],
		debug: false,
		post_params: {
			filename : '', 
			folder: '',
			width: 1,
			height: 1
		}
	})
		.bind('swfuploadLoaded', function(event){})
		.bind('fileQueued', function(event, file){
			// start the upload since it's queued
			$(this).swfupload('startUpload');
		})
		.bind('fileQueueError', function(event, file, errorCode, message){
			if(errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED)
				alert(message);
			if(errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT)
				alert('Fehler: Die Datei ist größer als '+maxImgSize);
			if(errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE)
				alert(message);
			if(errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE)
				alert(message);
		})
		.bind('fileDialogStart', function(event){})
		.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
			$(this).swfupload('setPostParams', {
				filename : getButtons().currentItem().basename, 
				folder: getButtons().currentItem().path,
				width: parseInt($('#btn_content_width').val()),
				height: parseInt($('#btn_content_height').val())
			});
		})
		.bind('uploadStart', function(event, file){})
		.bind('uploadProgress', function(event, file, bytesLoaded, bytesTotal){
			$('#btn_img_progress_bar_inner').css({
				width: (bytesLoaded/bytesTotal)*100+'%'
			});
		})
		.bind('uploadSuccess', function(event, file, serverData){
			$('#btn_img_progress_bar_inner').css({
				width: '0%'
			});
			var response = jQuery.parseJSON(serverData);
			if(response.result){
				if (response.pathname != null && response.pathname != '') {
					$('#btn_img_enable').attr('checked', true);
					$('#btn_img_path').val(response.pathname);
					$('#btn_img').attr('src',
							response.pathname+'?'+Math.floor(Math.random()*1001))
							.attr('width', Math.abs(Math.round(response.imagewidth*(300/475))))
							.attr('height',  Math.abs(Math.round(response.imageheight*(250/395))));
					getButtons().saveItem();
				}
			} else {
				if(debug) alert('Error while uploading image: '+response.error);
			}
		})
		.bind('uploadComplete', function(event, file){})
		.bind('uploadError', function(event, file, errorCode, message){
			if(errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED)
				alert(message);
			if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED)
				alert(message);
		});
};